package com.kania.todostack;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TodoSpaceActivity extends Activity implements View.OnClickListener {
	//각종 너비와 높이를 정의한다
	//너비
	int nwWindow; //x
	final int nwDate_d = 50; //왼쪽 날짜 너비 //d
	int nwDate;
	final int nWLeftStart_d = 10; // 왼쪽 여백 너비 //d
	int nWLeftStart;
	final int nwRightEnd_d = 20; // 오른쪽 여백 너비 //d
	int nwRightEnd;
	final int nwLeftGap_d = 2; // 각 todo마다 왼쪽 너비 //d
	int nwLeftGap;
	int nwSubject = 90; //각 todo 너비, !!!이 값은 재조정됨 
	//높이
	int nhWindow; //x
	int nhTodoStart; //x
	int nhTaskStart; //x
	int nhExpireStart; //x
	final int nhNormalGap_d = 2; // 점선이 없을 때의 간격 //d
	int nhNormalGap;
	final int nhLineGap_d = 1; // 점선이 있을 때 점선 위아래 간격 //d
	int nhLineGap;
	final int nhBoldLine_d = 2; // 날짜 todo와 할일 todo를 구분짓는 굵은 선 길이 //d
	int nhBoldLine;
	final int nhStrokeLine_d = 1; // 날짜 todo간 사이에 놓는 점선 길이 //d
	int nhStrokeLine;
	final int nhSubject_d = 12; // 각 주제의 이름 폰트 크기 //d
	int nhSubject;
	final int nhTodoRect_d = 10; // 각 todo의 네모 박스의 크기 //d
	int nhTodoRect;
	final int nhTodoText_d = 8; // 각 todo 내용 폰트 크기 //d
	int nhTodoText;
	//컨텐츠의 개수 변수,  기본값은 디폴트
	int nMaxSubject = 10; //defalt
	int nMaxDateTodo = 10;
	int nMaxTaskTodo = 5;
	int nMaxExpireTodo = 5;

	//날짜값 변수
	Calendar calToday;
	Calendar calTarget;
	Calendar calForPaint;
	
	//요일 string
	final String[] dayOfWeek = {"일", "월", "화", "수", "목", "금", "토"};

//	private SQLiteDatabase DBTodo;
//	private SQLiteDatabase DBSubject;


	//자료형
	ArrayList<SubjectData> listSubject = new ArrayList<SubjectData>();
	ArrayList<TodoData> listTodo = new ArrayList<TodoData>();

//	//전체 액티비티에 놓이는 뷰
//	TodoViewGroup tvg;
	
	//각 프레임의 레이아웃과 그 안의 버튼들
	RelativeLayout rlTodoInput, rlTodoInfo, rlSubInput, rlSubInfo;
	boolean bIsOpenRlTodoInput, bIsOpenRlTodoInfo, bIsOpenRlSubInput, bIsOpenRlSubInfo;
	Button btnTodoInfoDelete, btnTodoInfoCancel;
	Button btnTodoInputOK, btnTodoInputCancel;
	Button btnSubInfoDelete, btnSubInfoCancel;
	Button btnSubInputOK, btnSubInputCancel;
	
	//todo를 입력받을 시 쓰는 edit들과 변수
	EditText editYear;
	EditText editMonth;
	EditText editDay;
	EditText editTodoName;
	CheckBox checkTask;
	
	int nTodoInputSubNum;
	String sTodoInputYear;
	String sTodoInputMonth;
	String sTodoInputDate;
	String sTodoInputName;
	int nTodoInputFlag;
	
	//지울때 쓰이는 id저장 변수
	int nTodoDeleteID;
	int nSubDeleteID;
	int nSubDeleteSequence;
	
	//subject를 입력받을 때 쓰는 edit
	EditText editAddSubName;
	
	// 각 뷰에서 보내오는 event를 받는 handler
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			Bundle data = msg.getData();
			//Log.d("KANIA_LOG", "OK!");
			closeAllFrame();
			switch(data.getInt("eventtype")){
			case Type.EVENTTPYE_TODO_INFO:
				TextView textTodoName = (TextView)findViewById(R.id.textInfoTodo);
				textTodoName.setText(data.getString("todoinfo"));
				textTodoName.setTextColor((int)Type.COLOR_SUB[listSubject.get(data.getInt("subinfo")).getColor()]);
				nTodoDeleteID = data.getInt("id");
				rlTodoInfo.setVisibility(View.VISIBLE);
				bIsOpenRlTodoInfo = true;
				break;
			case Type.EVENTTPYE_TODO_INPUT: 
				nTodoInputSubNum = data.getInt("subnum");
				sTodoInputYear = calToday.get(Calendar.YEAR) + "";
				editYear.setText(sTodoInputYear);
				sTodoInputMonth = (calToday.get(Calendar.MONTH)+1) + "";
				editMonth.setText(sTodoInputMonth);
				sTodoInputDate = calToday.get(Calendar.DATE) + "";
				editDay.setText(sTodoInputDate);
				rlTodoInput.setVisibility(View.VISIBLE);
				bIsOpenRlTodoInput = true;
				break;
			case Type.EVENTTPYE_SUB_INFO: 
				TextView textSubName = (TextView)findViewById(R.id.textInfoSub);
				textSubName.setTextSize(20);
				textSubName.setText(data.getString("subinfo"));
				textSubName.setTextColor((int)Type.COLOR_SUB[listSubject.get(data.getInt("subnum")).getColor()]);
				nSubDeleteID = data.getInt("id");
				nSubDeleteSequence = data.getInt("subnum");
				rlSubInfo.setVisibility(View.VISIBLE);
				bIsOpenRlSubInfo = true;
				break;
			case Type.EVENTTPYE_SUB_INPUT:
				Log.d("KANIA_LOG", "OH!");
				rlSubInput.setVisibility(View.VISIBLE);
				bIsOpenRlSubInput = true;
				break;
			default:
				break;
			}
		}
	};
	
	//텍스트 입력 시 엔터 및 특수문자 를 받지 못하게 하는 필터를 생성한다
	protected InputFilter filterOnlyText = new InputFilter(){
		public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend){
			Pattern ps = Pattern.compile("^[ a-zA-Z0-9ㄱ-ㅎ가-�]+$");
			if(!ps.matcher(source).matches()){
				return "";
			}
			return null;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_todospace);

		//setContentView(tvg);
		
		//각 프레임을 얻어온다
		rlTodoInfo = (RelativeLayout)findViewById(R.id.layoutInfoTodoFrame);
		rlTodoInput = (RelativeLayout)findViewById(R.id.layoutInputTodoFrame);
		rlSubInfo = (RelativeLayout)findViewById(R.id.layoutInfoSubjectFrame);
		rlSubInput = (RelativeLayout)findViewById(R.id.layoutInputSubjectFrame);

		//각 프레임의 버튼들을 얻어온다.
		btnTodoInfoDelete = (Button)findViewById(R.id.btnInfoTodoDelete);
		btnTodoInfoDelete.setOnClickListener(this);
		btnTodoInfoDelete.setBackgroundColor((int)0x00FFFFFF);
		btnTodoInfoCancel = (Button)findViewById(R.id.btnInfoTodoCancel);
		btnTodoInfoCancel.setOnClickListener(this);
		btnTodoInfoCancel.setBackgroundColor((int)0x00FFFFFF);
		btnTodoInputOK = (Button)findViewById(R.id.btnInputTodoOK);
		btnTodoInputOK.setOnClickListener(this);
		btnTodoInputOK.setBackgroundColor((int)0x00FFFFFF);
		btnTodoInputCancel = (Button)findViewById(R.id.btnInputTodoCancel);
		btnTodoInputCancel.setOnClickListener(this);
		btnTodoInputCancel.setBackgroundColor((int)0x00FFFFFF);
		
		btnSubInfoDelete = (Button)findViewById(R.id.btnInfoSubDelete);
		btnSubInfoDelete.setOnClickListener(this);
		btnSubInfoDelete.setBackgroundColor((int)0x00FFFFFF);
		btnSubInfoCancel = (Button)findViewById(R.id.btnInfoSubCancel);
		btnSubInfoCancel.setOnClickListener(this);
		btnSubInfoCancel.setBackgroundColor((int)0x00FFFFFF);
		btnSubInputOK = (Button)findViewById(R.id.btnInputSubOK);
		btnSubInputOK.setOnClickListener(this);
		btnSubInputOK.setBackgroundColor((int)0x00FFFFFF);
		btnSubInputCancel = (Button)findViewById(R.id.btnInputSubCancel);
		btnSubInputCancel.setOnClickListener(this);
		btnSubInputCancel.setBackgroundColor((int)0x00FFFFFF);
		
		//Todo입력시 받는 에디트의 레퍼런스를 구한다
		editYear = (EditText)findViewById(R.id.editInputTodoYear);
		editMonth = (EditText)findViewById(R.id.editInputTodoMonth);
		editDay = (EditText)findViewById(R.id.editInputTodoDay);
		editTodoName = (EditText)findViewById(R.id.editInputTodoName);
			//필터를 추가해준다. 입력을 제한하기에...
		editTodoName.setFilters(new InputFilter[] {filterOnlyText});
		checkTask = (CheckBox)findViewById(R.id.checkInputTask);
		
		//subject 추가시 입력받는 이름 에디트를 가져온다
		editAddSubName = (EditText)findViewById(R.id.editInputSubName);
		
		modifySizeByScreen();
	}

	@Override
	protected void onResume(){
		super.onResume();

		modifyViewSize();
		
		paintTodoSpace();
	}
	
	@Override
	public void onClick(View v){
		switch(v.getId()){
		case R.id.btnInfoTodoDelete:
			Builder digDeleteTodo = new AlertDialog.Builder(TodoSpaceActivity.this);
			digDeleteTodo.setMessage("Remove?")
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					SQLiteDatabase DBTodo = (new TodoDBHelper(TodoSpaceActivity.this)).getWritableDatabase();
					DBTodo.execSQL("DELETE FROM todo WHERE _id=" + nTodoDeleteID + ";");
					DBTodo.close();
					paintTodoSpace();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			})
			.show();
			closeAllFrame();
			break;
		case R.id.btnInputTodoOK:
			sTodoInputYear = editYear.getText().toString();
			sTodoInputMonth = editMonth.getText().toString();
			sTodoInputDate = editDay.getText().toString();
			sTodoInputName = editTodoName.getText().toString();
			
			//각 날짜 스트링을 숫자로 바꾸고 날짜 예외체크
			int nYearCheck = Integer.parseInt(sTodoInputYear);
			int nMonthCheck = Integer.parseInt(sTodoInputMonth);
			int nDateCheck = Integer.parseInt(sTodoInputDate);
			
			if(nYearCheck > 0){
				int nRangeDate = -1;
				switch(nMonthCheck){
				case 1:
				case 3:
				case 5:
				case 7:
				case 8:
				case 10:
				case 12:
					nRangeDate = 31;
					break;
				case 4:
				case 6:
				case 9:
				case 11:
					nRangeDate = 30;
					break;
				case 2:
					if( ( (nYearCheck%4 == 0) && (nYearCheck%100 != 0) ) || (nYearCheck%400 == 0) ){
						nRangeDate = 29;
					}
					else{
						nRangeDate = 28;
					}
					break;
				default:
					Toast.makeText(this, "Do not execute! Input vaild Month(1~12)", Toast.LENGTH_SHORT).show();
					break;
				}
				if( (nDateCheck > 0) && (nDateCheck <= nRangeDate) ){
					SQLiteDatabase DBTodo = (new TodoDBHelper(this)).getWritableDatabase();
					//task가 아니라면
					if(checkTask.isChecked() == false){
						nTodoInputFlag = Type.TODOTPYE_DATE;
						//일단 추가하려는 날짜의 데이터가 있는가 검사한다.
						Cursor csTodo = DBTodo.rawQuery("SELECT todo FROM todo WHERE subject='" + nTodoInputSubNum + "' And year='" + sTodoInputYear + "' And month='" + sTodoInputMonth + "' And day='" + sTodoInputDate + "';", null);
						//			Log.d("KANIA_LOG", csCount.getCount() + "");
						if(csTodo.getCount() >= 1){
							if(csTodo.moveToNext()){
								String str = csTodo.getString(0) + " / " + sTodoInputName;
								DBTodo.execSQL("UPDATE todo SET todo='" + str + "' WHERE subject='" + nTodoInputSubNum + "' And year='" + sTodoInputYear + "' And month='" + sTodoInputMonth + "' And day='" + sTodoInputDate + "';");
							}
						}
						else{
							DBTodo.execSQL("INSERT INTO todo " 
									+ "(subject, year, month, day, todo, flag) " 
									+ "VALUES('" + nTodoInputSubNum + "' ,'" 
									+ sTodoInputYear + "' ,'" 
									+ sTodoInputMonth + "' ,'" 
									+ sTodoInputDate + "' ,'" 
									+ sTodoInputName + "' ,'"
									+ nTodoInputFlag + "');");
						}
						csTodo.close();
					}
					else{ //task라면
						nTodoInputFlag = Type.TODOTPYE_TASK;
						DBTodo.execSQL("INSERT INTO todo " 
								+ "(subject, year, month, day, todo, flag) " 
								+ "VALUES('" + nTodoInputSubNum + "' ,'" 
								+ "0000" + "' ,'" 
								+ "00" + "' ,'" 
								+ "00" + "' ,'" 
								+ sTodoInputName + "' ,'"
								+ nTodoInputFlag + "');");
						//체크박스도 초기화시킨다
						checkTask.setChecked(false);
					}
					editTodoName.setText("");
					DBTodo.close();

					closeAllFrame();
					paintTodoSpace();
				}
				else{
					Toast.makeText(this, "Do not execute! Input vaild Day(1~" + nRangeDate + ")", Toast.LENGTH_SHORT).show();
				}
			}
			else{
				Toast.makeText(this, "Do not execute! Input vaild Year.", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.btnInfoSubDelete:
			Builder digDeleteSub = new AlertDialog.Builder(TodoSpaceActivity.this);
			digDeleteSub.setMessage("Remove?")
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					SQLiteDatabase DBTodo = (new TodoDBHelper(TodoSpaceActivity.this)).getWritableDatabase();
					DBTodo.execSQL("DELETE FROM todo WHERE subject=" + nSubDeleteSequence + ";");
					DBTodo.close();
					SQLiteDatabase DBSubject = (new SubjectDBHelper(TodoSpaceActivity.this)).getWritableDatabase();
					DBSubject.execSQL("DELETE FROM subject WHERE _id=" + nSubDeleteID + ";");
					DBSubject.close();
					
					//모든 DB의 업데이트가 이루어져야함. **********************************
					paintTodoSpace();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			})
			.show();
			closeAllFrame();
			break;
		case R.id.btnInputSubOK:
			String subName = editAddSubName.getText().toString();
			SQLiteDatabase DBSubject = (new SubjectDBHelper(this)).getWritableDatabase();
			DBSubject.execSQL("INSERT INTO subject " 
									+ "(sequence, name, color) " 
									+ "VALUES(" + listSubject.size() + " ,'" 
									+ subName + "' ," 
									+ listSubject.size() + ");");
			editAddSubName.setText("");
			DBSubject.close();
			closeAllFrame();
			paintTodoSpace();
			break;
		case R.id.btnInfoTodoCancel:
		case R.id.btnInputTodoCancel:
		case R.id.btnInfoSubCancel:
		case R.id.btnInputSubCancel:
			closeAllFrame();
			break;
		}
	}

	public void paintTodoSpace(){
		//프레임을 초기화시킨다
		closeAllFrame();
		
		//뷰를 구성한다
		//밑바탕 뷰 그룹을 받아와 각 데이터에 따라 차일드 뷰를 만들어 추가한다.
		TodoViewGroup tvg = (TodoViewGroup)findViewById(R.id.viewgroupSpace);
		tvg.removeAllViews();

		//각 주제들의 데이터베이스를 읽어온 다음
		SQLiteDatabase DBSubject = (new SubjectDBHelper(this)).getWritableDatabase();
		Cursor csSubjec = DBSubject.rawQuery("SELECT _id, sequence, name, color FROM subject", null);
		//각 주제에 대한 배열에 넣음
		listSubject.clear();
		while(csSubjec.moveToNext()){
			int id = csSubjec.getInt(0);
			int sequence = csSubjec.getInt(1);
			String name = csSubjec.getString(2);
			int color = csSubjec.getInt(3);
			listSubject.add(new SubjectData(id, sequence, name, color));
		}
		csSubjec.close();
		DBSubject.close();

		//각 할일들의 데이터베이스를 읽어온 다음
		SQLiteDatabase DBTodo = (new TodoDBHelper(this)).getWritableDatabase();
		Cursor csTodo = DBTodo.rawQuery("SELECT _id, subject, year, month, day, todo, flag FROM todo", null);
		//각 할일에 대한 배열에 넣음
		listTodo.clear();
		while(csTodo.moveToNext()){
			int id = csTodo.getInt(0);
			int subject = csTodo.getInt(1);
			int year = csTodo.getInt(2);
			int month = csTodo.getInt(3);
			int day = csTodo.getInt(4);
			String todo = csTodo.getString(5);
			int flag = csTodo.getInt(6);
			listTodo.add(new TodoData(id, subject, year, month, day, todo, flag));
		}
		csTodo.close();
		DBTodo.close();
		
		// 기간이 지난 Todo에 대하여 expired 플래그를 정의한다.
		// __unimplement

		//subject가 0이 아니라면치수를 구한다.
		
		modifySizeByScreen();
		
		nwWindow = getLcdSIzeWidth();
		nMaxSubject = (nwWindow / 100) - 1;
		if(listSubject.size() > 0){
			nwSubject = ( (nwWindow - (nWLeftStart + nwDate + nwRightEnd) ) / listSubject.size() ) - nwLeftGap; 
		}
		else{
			nwSubject = 0;
		}
		//todo를 몇개 놓을건지를 구한다 
		nMaxDateTodo = getLcdSIzeHeight() / 100;
		nMaxTaskTodo = nMaxDateTodo / 2;
		nMaxExpireTodo = nMaxDateTodo / 2;
		//시작할 높이를 구함. 윈도우의 밑에서 40%일때
		nhTodoStart = ( getLcdSIzeHeight() * 7 ) / 10;
		//높이에 대하여 task 와 expire를 놓을 지점을 구한다.
		nhTaskStart = nhTodoStart - ( (nhLineGap*2+nhTodoRect+nhStrokeLine ) * nMaxDateTodo + 2);
		nhExpireStart = nhTodoStart + (nhNormalGap + nhSubject + nhNormalGap);
		
		//점선을 그을 위치를 지정한다
		tvg.nDateLeftStart = nWLeftStart;
		tvg.nDateRightEnd = nwWindow - nwRightEnd;

		//오늘 날짜를 받고 시간을 0시 0분 0초 0밀리초로 초기화시키고
		calToday = Calendar.getInstance();
		//미리 타겟 날짜에 대한 구조체를 받아옴
		calTarget = Calendar.getInstance();
		calToday.set(Calendar.HOUR_OF_DAY, 0);
		calToday.set(Calendar.MINUTE, 0);
		calToday.set(Calendar.SECOND, 0);
		calToday.set(Calendar.MILLISECOND, 0);
		//출력을 위해 캘린더를 하나 더 초기화한다
		calForPaint = Calendar.getInstance();
		/*
				calTarget.set(Calendar.HOUR_OF_DAY, 0);
				calTarget.set(Calendar.MINUTE, 0);
				calTarget.set(Calendar.SECOND, 0);
				calTarget.set(Calendar.MILLISECOND, 0);
		 */


		for(TodoData td : listTodo){
			//기간이 지난 todo들은 exfired 로 처리하고 처리한다
			if(td.getFlag() == Type.TODOTPYE_DATE){
				calTarget.set(Calendar.YEAR, td.getYear());
				calTarget.set(Calendar.MONTH, td.getMonth()-1);
				calTarget.set(Calendar.DATE, td.getDay());
				calTarget.set(Calendar.HOUR_OF_DAY, 0);
				calTarget.set(Calendar.MINUTE, 0);
				calTarget.set(Calendar.SECOND, 0);
				calTarget.set(Calendar.MILLISECOND, 0);
				int nDifDays = differenceDate(calTarget.getTimeInMillis(), calToday.getTimeInMillis());
				if(nDifDays < 0){
					td.setFlag(Type.TODOTPYE_EXPIRED); // 기간이 지는 것들은 flag를 -1(exfire)로 바꾼다
				}
			}
			
			if(td.getFlag() == Type.TODOTPYE_TASK){ // task
				TodoView tv = new TodoView(this, td, mHandler);
				//l r 값을 정한다.
				tv.left = nWLeftStart + nwDate + ( (td.getSubject()) * (nwLeftGap+nwSubject) );
				tv.right = tv.left + nwSubject;
				tv.bottom = nhTaskStart - ( (nhNormalGap+nhTodoRect) * listSubject.get(td.getSubject()).nTaskCount);
				tv.top = tv.bottom - nhTodoRect;
				listSubject.get(td.getSubject()).nTaskCount += 1;
				tv.setBackgroundColor((int)Type.COLOR_SUB[listSubject.get(td.getSubject()).getColor()]);
				tvg.addView(tv);
			}
			else if(td.getFlag() == Type.TODOTPYE_EXPIRED){ //expire
				TodoView tv = new TodoView(this, td, mHandler);
				//l r 값을 정한다.
				tv.left = nWLeftStart + nwDate + ( (td.getSubject()) * (nwLeftGap+nwSubject) );
				tv.right = tv.left + nwSubject;
				tv.top = nhExpireStart + ( (nhNormalGap+nhTodoRect) * listSubject.get(td.getSubject()).nExpireCount);
				tv.bottom = tv.top + nhTodoRect;
				listSubject.get(td.getSubject()).nExpireCount += 1;
//				tv.setBackgroundColor((int)0xFF999999);
				tv.setBackgroundColor((int)Type.COLOR_SUB[listSubject.get(td.getSubject()).getColor()]);
				tvg.addView(tv);
			}
			else{ // date
				
				calTarget.set(Calendar.YEAR, td.getYear());
				calTarget.set(Calendar.MONTH, td.getMonth()-1);
				calTarget.set(Calendar.DATE, td.getDay());
				calTarget.set(Calendar.HOUR_OF_DAY, 0);
				calTarget.set(Calendar.MINUTE, 0);
				calTarget.set(Calendar.SECOND, 0);
				calTarget.set(Calendar.MILLISECOND, 0);
				int nDifDays = differenceDate(calTarget.getTimeInMillis(), calToday.getTimeInMillis());
				if(nDifDays >= 0 && nDifDays < nMaxDateTodo){ // 범위에 있을 때만 그린다.
					TodoView tv = new TodoView(this, td, mHandler);
					//l r 값을 정한다.
					tv.left = nWLeftStart + nwDate + ( (td.getSubject()) * (nwLeftGap+nwSubject) );
					tv.right = tv.left + nwSubject;
					tv.bottom = nhTodoStart - ( (nhLineGap + nhTodoRect + nhLineGap + nhStrokeLine) * nDifDays );
					tv.top = tv.bottom - nhTodoRect;
					//만약 오늘이하면 빨간색 나머진 색상별로
					if(nDifDays == 0){
						tv.setBackgroundColor((int)0xFFFF0000);
					}
					else{
						tv.setBackgroundColor((int)Type.COLOR_SUB[listSubject.get(td.getSubject()).getColor()]);
					}
					tvg.addView(tv);
				}
			}
		}
		
		for(SubjectData sd : listSubject){
			SubjectView sv = new SubjectView(this, sd, mHandler);
			sv.left = nWLeftStart + nwDate + ( (sd.getSequenceNumber()) * (nwLeftGap+nwSubject) );
			sv.right = sv.left + nwSubject;
			sv.top = nhTodoStart + nhNormalGap;
			sv.bottom = sv.top + nhSubject;
			sv.setTextColor(Type.COLOR_SUB[sd.getColor()]);
			tvg.addView(sv);
		}
		
		//그릴 날짜를 뷰 그룹에 지정해준다.
		tvg.initDateList();
		//tvg.nFontSize = nhTodoText;
		//만료 텍스트 뷰를 지정해준다
		{
			DateView dv = new DateView(this, "Delayed ");
			dv.left = nWLeftStart;
			dv.right = nWLeftStart + nwDate;
			dv.top = nhExpireStart;
			dv.bottom = dv.top + nhTodoRect;
			tvg.addView(dv);
		}
		for(int i = 0; i < nMaxDateTodo; i++){
			String sMonth, sDay;
			if( (calForPaint.get(Calendar.MONTH)+1) < 10){
				sMonth = (calForPaint.get(Calendar.MONTH)+1) + "  ";
			}else{
				sMonth = (calForPaint.get(Calendar.MONTH)+1) + "";
			}
			if( calForPaint.get(Calendar.DATE) < 10){
				sDay = "  " + calForPaint.get(Calendar.DATE);
			}else{
				sDay = "" + calForPaint.get(Calendar.DATE);
			}
			DateView dv = new DateView(this, sMonth + "-" + sDay + " " + dayOfWeek[calForPaint.get(Calendar.DAY_OF_WEEK)-1] + "  ");
			dv.left = nWLeftStart;
			dv.right = nWLeftStart + nwDate;
			dv.bottom = nhTodoStart - ( (nhLineGap + nhTodoRect + nhLineGap + nhStrokeLine) * i );
			dv.top = dv.bottom - nhTodoRect;
			//tvg.addDateList((calForPaint.get(Calendar.MONTH)+1) + "-" + calForPaint.get(Calendar.DATE) + "  ");
			if(i == 0){
				dv.setTextColor((int)0xFFFF0000);
			}
			tvg.addView(dv);
			calForPaint.add(Calendar.DATE, 1);
		}
		
		//subject 추가를 위한 버튼을 넣어준다
		TextView btnAddSub = new TextView(this);
		btnAddSub.setBackgroundColor((int)0x00000000);
		btnAddSub.setTextSize(12);
		btnAddSub.setText("+");
		btnAddSub.setGravity(Gravity.CENTER);
		btnAddSub.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Message msg = Message.obtain();
				Bundle data = new Bundle();
				data.putInt("eventtype", Type.EVENTTPYE_SUB_INPUT);
				msg.setData(data);
				mHandler.sendMessage(msg);
			}
		});
		
		
		tvg.addView(btnAddSub);
		
		tvg.invalidate();
	}
	
	
	
	public int differenceDate(long target, long today){
		int dif = 0;
		dif = (int)((target-today) / (1000*60*60*24));
		return dif;
	}
	
	public void closeAllFrame(){
		//키보드를 내리기 위함임.
		InputMethodManager inputManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);

		if(bIsOpenRlSubInfo == true){
			rlSubInfo.setVisibility(View.INVISIBLE);
			bIsOpenRlSubInfo = false;
		}
		if(bIsOpenRlSubInput == true){
			rlSubInput.setVisibility(View.INVISIBLE);
			bIsOpenRlSubInput = false;
			editAddSubName.setText("");
			inputManager.hideSoftInputFromWindow(editAddSubName.getWindowToken(),0);
		}
		if(bIsOpenRlTodoInfo == true){
			rlTodoInfo.setVisibility(View.INVISIBLE);
			bIsOpenRlTodoInfo = false;
		}
		if(bIsOpenRlTodoInput == true){
			rlTodoInput.setVisibility(View.INVISIBLE);
			bIsOpenRlTodoInput = false;
			editTodoName.setText("");
			inputManager.hideSoftInputFromWindow(editTodoName.getWindowToken(),0);
			//체크박스도 초기화
			checkTask.setChecked(false);
		}
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void modifySizeByScreen(){
//		nwRightEnd = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160.0f, getResources().getDisplayMetrics());
		nwDate = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nwDate_d, getResources().getDisplayMetrics());
		nWLeftStart = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nWLeftStart_d, getResources().getDisplayMetrics());
		nwRightEnd = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nwRightEnd_d, getResources().getDisplayMetrics());
		nwLeftGap = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nwLeftGap_d, getResources().getDisplayMetrics());

		nhNormalGap = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nhNormalGap_d, getResources().getDisplayMetrics());
		nhLineGap = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nhLineGap_d, getResources().getDisplayMetrics());
		nhBoldLine = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nhBoldLine_d, getResources().getDisplayMetrics());
		nhStrokeLine = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nhStrokeLine_d, getResources().getDisplayMetrics());
		nhSubject = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nhSubject_d, getResources().getDisplayMetrics());
		nhTodoRect = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nhTodoRect_d, getResources().getDisplayMetrics());
		nhTodoText = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, nhTodoText_d, getResources().getDisplayMetrics());
	}
	
	public void modifyViewSize(){
//		btnTodoInfoDelete.setHeight(nhSubject);
//		btnTodoInfoCancel.setHeight(nhSubject);
//		btnTodoInputOK.setHeight(nhSubject);
//		btnTodoInputCancel.setHeight(nhSubject);
//		btnSubInfoDelete.setHeight(nhSubject);
//		btnSubInfoCancel.setHeight(nhSubject);
//		btnSubInputOK.setHeight(nhSubject);
//		btnSubInputCancel.setHeight(nhSubject);
		editYear.setHeight(nhSubject);
		editMonth.setHeight(nhSubject);
		editDay.setHeight(nhSubject);
		editTodoName.setHeight(nhSubject);
		checkTask.setHeight(nhSubject);
		editAddSubName.setHeight(nhSubject);
		checkTask.setHeight(nhSubject);
		
		btnTodoInfoDelete.setTextSize(nhTodoText);
		btnTodoInfoCancel.setTextSize(nhTodoText);
		btnTodoInputOK.setTextSize(nhTodoText);
		btnTodoInputCancel.setTextSize(nhTodoText);
		btnSubInfoDelete.setTextSize(nhTodoText);
		btnSubInfoCancel.setTextSize(nhTodoText);
		btnSubInputOK.setTextSize(nhTodoText);
		btnSubInputCancel.setTextSize(nhTodoText);
		editYear.setTextSize(nhTodoText);
		editMonth.setTextSize(nhTodoText);
		editDay.setTextSize(nhTodoText);
		editTodoName.setTextSize(nhTodoText);
		checkTask.setTextSize(nhTodoText);
		editAddSubName.setTextSize(nhTodoText);
		checkTask.setTextSize(nhTodoText);
	}

	public int getLcdSIzeWidth()
	{
		return ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
	}   //가로 크기

	public int getLcdSIzeHeight()
	{
		return ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight();
	}    // 세로 크기

}